<?php
namespace app\common\job;

use app\admin\model\Form1;
use app\admin\model\Form2;
use app\admin\model\Form3;
use app\admin\model\Form5;
use app\admin\model\Notify;
use app\common\controller\Sms;
use think\facade\Db;
use think\facade\Log;
use think\queue\Job;
use think\Exception;

class SendSms
{
    public function fire(Job $job, $data)
    {
		try {
			//类型：上午or下午
			$tid = 1;
			(date('H') >= 12) && $tid = 2;
			switch ($data['type']) {
				case 1:
					//返沙体温上报14天
					$result = self::common($data, Form1::class, 28, $tid);
					break;
				case 2:
					//疫苗异常询问2天
					//类型覆盖
					$tid = 4;
					$result = self::common($data, Form2::class, 2, $tid);
					break;
				case 3:
					// 购药人员体温上报14天
					$result = self::common($data, Form3::class, 28, $tid);
					break;
				case 4:
					// 集中隔离人员体温上报21天
					$result = self::common($data, Form5::class, 42, $tid);
					break;
				case 5:
					//核酸检测通知
					//类型覆盖
					$tid = 5;
					$result = self::common($data, Form5::class, 28, $tid);
					break;
			}
			if ($result !== 'success') {
				// 记录短信错误日志
				Log::write($result);
			}
		} catch(\Exception $e) {
			// 记录整体错误日志
			Log::write('错误：'.$e->getMessage());
		}
        
        // 无论是否发送成功，都删除任务，不再重试
        $job->delete();
    }

    /**
     * 发送短信公共方法
     * @param $res
     * @param $class
     * @param int $number
     * @param int $tid
     * @return bool|string
     */
    private function common($res, $class, int $number, int $tid)
    {
        //开始发送
        $result = Sms::send($tid, $res['list']);

        //发送后置逻辑
        if ($result == 'success') {
            $keys = array_keys($res['list']);

            //更新发送时间、已发次数
            $class::whereIn('id', $keys)->update([
                'count'     =>  Db::raw('count+1'),
                'sms_time'  =>  time(),
            ]);

            //把所有刚好number次的，全部标注为已解除
            $class::where('count', '>=', $number)
                ->whereIn('id', $keys)
                ->update([
                    'status'  =>  1,
                ]);
				
            //插入通知记录
            $data = $class::whereIn('id', $keys)->field('mobile,id_card,community')->select();
            foreach ($data as $v) {
                Notify::create([
                    'types'	   =>  $res['type'],
                    'mobile'   =>  $v->mobile,
                    'id_card'  =>  $v->id_card,
                    'community'=>  $v->community,
                ]);
            }
        }
        return $result;
    }
}